package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.BaseException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.SetmealVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author zzw
 * @date 2025/4/29
 * @description 套餐管理实现类
 */
@Service
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private DishMapper dishMapper;

    @Override
    public PageResult<SetmealVO> page(SetmealPageQueryDTO setmealPageQueryDTO) {
        // 1.设置分页参数
        PageHelper.startPage(setmealPageQueryDTO.getPage(), setmealPageQueryDTO.getPageSize());

        // 2.执行分页查询
        Page<SetmealVO> page = setmealMapper.page(setmealPageQueryDTO);

        // 3.返回封装后的结果
        return new PageResult<>(page.getTotal(), page.getResult());
    }

    /**
     * 新增套餐
     *
     * @param setmealDTO 新增套餐
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);

        // 1.添加套餐基本信息
        setmealMapper.insert(setmeal);

        // 2.添加套餐菜品关系
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> {
            setmealDish.setSetmealId(setmeal.getId());
        });
        setmealDishMapper.insertBatch(setmealDishes);
    }

    /**
     * 修改套餐
     *
     * @param setmealDTO 套餐DTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SetmealDTO setmealDTO) {
        // 1.修改套餐基本信息
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);
        setmealMapper.update(setmeal);

        // 2.删除套餐中的套餐菜品关系
        setmealDishMapper.deleteBySetmealIds(new Long[]{setmealDTO.getId()});

        // 3.批量插入套餐菜品关系
        setmealDTO.getSetmealDishes().forEach(setmealDish -> setmealDish.setSetmealId(setmealDTO.getId()));
        setmealDishMapper.insertBatch(setmealDTO.getSetmealDishes());
    }

    /**
     * 根据id查询套餐
     *
     * @param id 套餐id
     * @return SetmealVO
     */
    @Override
    public SetmealVO getById(Long id) {
        return setmealMapper.getById(id);
    }

    /**
     * 套餐启售、停售
     *
     * @param status 状态
     * @param id     套餐id
     */
    @Override
    public void status(Integer status, Long id) {
        // 1. 根据id查询套餐信息
        SetmealVO setmealVO = setmealMapper.getById(id);
        if (setmealVO == null) {
            throw new BaseException("套餐不存在");
        }

        List<SetmealDish> setmealDishes = setmealVO.getSetmealDishes();
        if (setmealDishes != null && !setmealDishes.isEmpty()) {
            // 获取所有菜品ID
            List<Long> dishIds = setmealDishes.stream().map(SetmealDish::getDishId).collect(Collectors.toList());

            // 批量查询菜品信息
            List<Dish> dishes = dishMapper.getByIds(dishIds);

            // 检查是否有菜品停售
            boolean hasDisabledDish = dishes.stream()
                                            .anyMatch(dishVO -> Objects.equals(
                                                    dishVO.getStatus(),
                                                    StatusConstant.DISABLE
                                                                              ));

            if (hasDisabledDish) {
                throw new BaseException(MessageConstant.SETMEAL_ENABLE_FAILED);
            }
        }

        // 2. 修改套餐状态
        Setmeal setmeal = new Setmeal();
        setmeal.setId(id);
        setmeal.setStatus(status);
        setmealMapper.update(setmeal);
    }

    /**
     * 批量删除套餐
     *
     * @param ids 套餐id数组
     */
    @Override
    @Transactional
    public void deleteBatch(Long[] ids) {
        if (ids == null || ids.length == 0) {
            throw new DeletionNotAllowedException("请选择要删除的套餐后再删除");
        }
        // 1.检查套餐是否启售
        for (Long id : ids) {
            SetmealVO setmealVO = setmealMapper.getById(id);
            if (setmealVO.getStatus() == 1) {
                throw new DeletionNotAllowedException("当前套餐正在售中，不能删除");
            }
        }
        // 2.删除套餐菜品关系
        setmealDishMapper.deleteBySetmealIds(ids);

        // 3.删除套餐
        setmealMapper.deleteBatch(ids);
    }

    /**
     * 获取套餐列表
     *
     * @param categoryId 分类id
     * @return List<Setmeal>
     */
    @Override
    public List<Setmeal> list(Long categoryId) {
        Integer status = StatusConstant.ENABLE;
        return setmealMapper.list(categoryId, status);
    }

    @Override
    public List<DishItemVO> getDishItemById(Long setmealId) {
        return setmealMapper.getDishItemById(setmealId);
    }
}
